package com.example.mountain;

import android.R.layout;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;

public class Compass extends Activity {
	SensorManager mySensorManager;
	CompassView compassView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		compassView = new CompassView(this);
		setContentView(compassView);
		mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		compassView.setBackgroundResource(R.drawable.ba);
		
	}

	@Override
	protected void onResume() {
		super.onResume();

		mySensorManager.registerListener(compassView,
				mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);

	}

	@Override
	protected void onPause() {
		super.onPause();
		mySensorManager.unregisterListener(compassView);
	}

	class CompassView extends View implements SensorEventListener {
		float azimuth;
		Paint textPnt = new Paint();
		Bitmap compass;

		public CompassView(Context context) {
			super(context);
			textPnt.setColor(Color.BLACK);
			textPnt.setTextSize(40);
			textPnt.setAntiAlias(true);
			
			
			compass = BitmapFactory.decodeResource(getResources(),
					R.drawable.compass);
		
		}

		@SuppressWarnings("deprecation")
		@Override
		public void onSensorChanged(SensorEvent event) {
			float[] v = event.values;

			switch (event.sensor.getType()) {
			case Sensor.TYPE_ORIENTATION:
				if (azimuth != v[0]) {
					azimuth = v[0];
					invalidate();
				}
				break;
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}

		@Override
		protected void onDraw(Canvas canvas) {

			Paint Pnt = new Paint();
			Pnt.setAntiAlias(true);
			Matrix matrix = new Matrix();

			matrix.postRotate(-azimuth, compass.getWidth() / 2,
					compass.getHeight() / 2);
			matrix.postTranslate(50, 80);
			canvas.drawBitmap(compass, matrix, Pnt);

			canvas.drawText("방위각:" + (int) azimuth, 130, 60, textPnt);
		}

	}

}